Grokking Amazon Coding Interview
Rate this course
Ask Author
Contribute
Back to course home

0% completed

Vote For New Content
Introduction
Who Should Take This Course?
Amazon Easy Problems
Redistribute Characters to Make All Strings Equal (easy)
Solution: Redistribute Characters to Make All Strings Equal
Longest Common Prefix (easy)
Solution: Longest Common Prefix
Make Array Zero by Subtracting Equal Amounts (easy)
Solution: Make Array Zero by Subtracting Equal Amounts
Leaf-Similar Trees (easy)
Solution: Leaf-Similar Trees
Path Crossing (easy)
Solution: Path Crossing
Special Array With X Elements Greater Than or Equal X (easy)
Solution: Special Array With X Elements Greater Than or Equal X
Relative Sort Array (easy)
Solution: Relative Sort Array
Transpose Matrix (easy)
Solution: Transpose Matrix
Find Common Characters (easy)
Solution: Find Common Characters
Fizz Buzz (easy)
Solution: Fizz Buzz
Increasing Order Search Tree (easy)
Solution: Increasing Order Search Tree
Largest Odd Number in String (easy)
Solution: Largest Odd Number in String
Best Time to Buy and Sell (easy)
Solution: Best Time to Buy and Sell Stock
Take Gifts From the Richest Pile(easy)
Solution: Take Gifts From the Richest Pile
Remove Duplicates from Sorted List (easy)
Solution: Remove Duplicates from Sorted List
Maximum Length of Subarray With Positive Product (medium)
Solution: Maximum Length of Subarray With Positive Product
Largest Submatrix With Rearrangements (medium)
Solution: Largest Submatrix With Rearrangements
Count the Number of Good Subarrays (medium)
Solution: Count the Number of Good Subarrays
Minimum Suffix Flips (medium)
Solution: Minimum Suffix Flips
Minimum Number of Operations to Make Array Empty (medium)
Solution: Minimum Number of Operations to Make Array Empty
Next Greater Element II (medium)
Solution: Next Greater Element II
Make Sum Divisible by P (medium)
Solution: Make Sum Divisible by P
Rotting Oranges (medium)
Solution: Rotting Oranges
Minimum Deletions to Make Character Frequencies Unique (medium)
Solution: Minimum Deletions to Make Character Frequencies Unique
Minimum Adjacent Swaps to Make a Valid Array (medium)
Solution: Minimum Adjacent Swaps to Make a Valid Array
Reverse Integer (medium)
Solution: Reverse Integer
Maximize Distance to Closest Person (medium)
Solution: Maximize Distance to Closest Person
Split Linked List in Parts (medium)
Solution: Split Linked List in Parts
Maximum Difference Between Node and Ancestor (medium)
Solution: Maximum Difference Between Node and Ancestor
Deepest Leaves Sum (medium)
Solution: Deepest Leaves Sum
The kth Factor of n (medium)
Solution: The kth Factor of n
Coin Change II (medium)
Solution: Coin Change II
Sum of Subarray Minimums (medium)
Solution: Sum of Subarray Minimums
Valid Sudoku (medium)
Solution: Valid Sudoku
Longest Increasing Subsequence (medium)
Solution: Longest Increasing Subsequence
Next Permutation (medium)
Solution: Next Permutation
Subsets (medium)
Solution: Subsets
Combination Sum (medium)
Solution: Combination Sum
Number of Provinces (medium)
Solution: Number of Provinces
Number of Islands (medium)
Solution: Number of Islands
Constrained Subsequence Sum (hard)
Solution: Constrained Subsequence Sum
Number of Valid Subarrays (hard)
Solution: Number of Valid Subarrays
Count Vowels Permutation (hard)
Solution: Count Vowels Permutation
Concatenated Words (hard)
Solution: Concatenated Words
Minimum Replacements to Sort the Array (hard)
Solution: Minimum Replacements to Sort the Array
Count All Valid Pickup and Delivery Options (hard)
Solution: Count All Valid Pickup and Delivery Options
Length of the Longest Valid Substring (hard)
Solution: Length of the Longest Valid Substring
Count Array Pairs Divisible by K (hard)
Solution: Count Array Pairs Divisible by K
Word Ladder (hard)
Solution: Word Ladder
Path with Maximum Sum (hard)
Solution: Path with Maximum Sum
Solution: Find Common Characters

Problem Statement

Given a strings array words, return a character array results containing all characters (including duplicates), which are common in all strings of words. You may return characters in any order.

Examples

  • Example 1:

    • Input: words = ["glean","angle","angel","galen","lange"]
    • Expected Output: ["a","e","g","l","n"]
    • Justification: The letters 'a', 'e', 'g', 'l', and 'n' are present in all five words. Each of these letters appears at least once in every word, making them common to all strings.
  • Example 2:

    • Input: words = ["danday","candya","ahand"]
    • Expected Output: ["a","a","d","n"]
    • Justification: The letters 'a', 'a', 'd', and 'n' are common in all three words, each appearing at least once in every word.
  • Example 3:

    • Input: words = ["race","care","ac"]
    • Expected Output: ["a","c""]
    • Justification: The letters 'a', and 'c' are present in all three words. Each of these letters appears at least once in every word, so they are included in the output list.

Solution

To solve this problem, we'll adopt a character frequency mapping approach. The core idea is to create frequency maps for each string in the input list, tracking how often each character appears. Then, we'll compare these frequency maps to identify characters common to all strings, focusing on the minimum frequency of each character. This method ensures that we only include characters that appear in every string, and do so according to their least occurrence across all strings. This approach is effective because it directly addresses the problem's requirements, ensuring accuracy and efficiency by leveraging frequency counts to streamline comparisons and minimize unnecessary computations.

Our strategy involves iterating through each string in the input list, updating a global frequency map that reflects the minimum occurrences of each character across all strings examined so far. By starting with the first string's frequency map and adjusting it based on subsequent strings, we guarantee that only common characters with their minimum frequencies are retained. This method is chosen for its simplicity and effectiveness in handling varying string lengths and character distributions, ensuring a solution that is both scalable and adaptable to different input sizes.

Step-by-step Algorithm

  1. Initialize a global frequency map (minFreq) with 26 elements, one for each letter of the alphabet, and set each value to the maximum integer value to represent the minimum frequency of each character across all strings.

  2. Iterate over each word in the input array:

    • Create a local frequency map (charFreq) for the current word, initializing all values to 0.
    • For each character in the current word, increment its corresponding frequency in the local frequency map.
    • After processing the word, update the global frequency map by comparing it with the local frequency map. For each character, if its frequency in the local map is less than what's currently in the global map, update the global map with the local map's frequency.
  3. After processing all words, iterate through the global frequency map:

    • For each character that has a frequency greater than 0, add it to the result list as many times as its frequency.
  4. Return the result list containing all common characters with their minimum frequency.

Algorithm Walkthrough

Let's consider the input: words = ["race", "care", "ac"]

Initial Setup

  • Global Map is initialized with infinity (or a very high number) for all alphabet characters to represent that we haven't encountered any characters yet.

Iteration 1: Processing "race"

  • Local Map for "race": {'r':1, 'a':1, 'c':1, 'e':1}
  • Global Map Update:
    • Since it's the first word, the Global Map is updated to match the Local Map of "race".
    • Global Map Now: {'r':1, 'a':1, 'c':1, 'e':1}

Iteration 2: Processing "care"

  • Local Map for "care": {'c':1, 'a':1, 'r':1, 'e':1}
  • Global Map Comparison and Update:
    • We compare each character's frequency in "care" with the Global Map.
    • Since all frequencies match and are not less than those in the Global Map, no update is needed.
    • Global Map Remains: {'r':1, 'a':1, 'c':1, 'e':1}

Iteration 3: Processing "ac"

  • Local Map for "ac": {'a':1, 'c':1}
    • Note: 'r' and 'e' are not present in "ac", so their frequencies in the Local Map for "ac" are considered 0.
  • Global Map Comparison and Update:
    • We update the Global Map based on the Local Map for "ac".
    • The characters 'r' and 'e' are not present in "ac", so their global frequencies are effectively set to 0 (or they are removed from consideration).
    • For 'a' and 'c', the frequencies in both the Global Map and the Local Map for "ac" match and are 1.
    • Global Map Now: {'a':1, 'c':1}
      • Only 'a' and 'c' remain with their frequencies unchanged because they are the only characters present in all words so far.

Final Result

  • Global Map: {'a':1, 'c':1}
  • The final result is derived from the Global Map, resulting in the characters ["a", "c"] as the common characters found in all input strings with the minimum frequency across all strings.

Code

Java
Saved to Cloud

. . . .

Complexity Analysis

Time Complexity

, where N is the number of strings in the array and L is the average length of a string.

  • For each string, we count the frequency of each character, which takes time.
  • We then iterate over the frequency array of length 26 (constant time, hence ignored in the complexity analysis) for each of the N strings to update the global minimum frequency counts.
  • Therefore, the total time complexity is dominated by the iteration over each string and its characters.

Space Complexity

O(1), as we use a fixed-size integer array of length 26 to store the frequency of each letter from 'a' to 'z', which is a constant space requirement. Thus, the auxiliary space used by the algorithm is constant.

Find Common Characters (easy)
Fizz Buzz (easy)
Mark as Completed

On this page

Problem Statement

Examples

Solution

Step-by-step Algorithm

Algorithm Walkthrough

Final Result

Code

Complexity Analysis

Time Complexity

Space Complexity